<template>
  <div class="app-container">
    <div class="search-container">
      <el-form :model="searchParam" :inline="true">
        <el-form-item label="分类">
          <el-input
            v-model="searchParam.classification"
            placeholder="请输入分类"
            clearable
            @keyup.enter="search"
          />
        </el-form-item>
        <el-form-item label="产品">
          <el-input
            v-model="searchParam.materialCode"
            placeholder="请选择产品"
            clearable
            readonly
            @click="showWorkOrderSelect"
          >
            <template #append>
              <el-button @click="resetMaterial"> 清除 </el-button>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="search"
            ><i-ep-search />搜索</el-button
          >
          <el-button @click="reset"><i-ep-refresh />重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never" class="table-container">
      <template #header>
        <el-button type="success" plain @click="openDialog()"
          ><i-ep-plus />新增</el-button
        >
        <el-button type="primary" @click="materialImport">
          <template #icon><i-ep-upload /></template>导入
        </el-button>
        <el-button
          class="ml-3"
          @click="
            useDownload(
              '/mes/mespurchasematerialconfig/export',
              '原材料到货配置',
              searchParam
            )
          "
        >
          <template #icon><i-ep-download /></template>导出</el-button
        >
      </template>

      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="tableData"
        highlight-current-row
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <template v-for="item in tableColumns" :key="item">
          <TableColumn v-if="item.prop && item.isShow" :column="item">
            <template v-for="slot in Object.keys($slots)" #[slot]="scope">
              <slot :name="slot" v-bind="scope"></slot>
            </template>
          </TableColumn>
        </template>
        <!-- <el-table-column
          label="分类"
          prop="classification"
          min-width="100"
          show-overflow-tooltip
        />
        <el-table-column
          label="物料名称"
          prop="materialName"
          min-width="100"
          show-overflow-tooltip
        />
        <el-table-column
          label="单位"
          prop="unit"
          min-width="100"
          show-overflow-tooltip
          align="center"
        >
          <template #default="scope">
            {{ useDictionary("MeasurementUnit", scope.row.unit) }}
          </template>
        </el-table-column>
        <el-table-column
          label="采购周期"
          prop="purchasingCycle"
          min-width="100"
          show-overflow-tooltip
        /> -->
        <!-- <el-table-column
          label="安全系数"
          prop="safetyFactor"
          min-width="100"
          show-overflow-tooltip
        /> -->
        <!-- <el-table-column
          label="采购影响(产能)"
          prop="produce"
          min-width="100"
          show-overflow-tooltip
        />
        <el-table-column
          label="采购影响(天气)"
          prop="weather"
          min-width="100"
          show-overflow-tooltip
        />
        <el-table-column
          label="采购影响(质量异常)"
          prop="quality"
          min-width="120"
          show-overflow-tooltip
        />
        <el-table-column
          label="保质期（月）"
          prop="shelfLife"
          min-width="100"
          show-overflow-tooltip
        />
        <el-table-column
          label="最小采购量"
          prop="minimumPurchaseQuantity"
          min-width="100"
          show-overflow-tooltip
        />
        <el-table-column
          label="备注"
          prop="remarks"
          min-width="100"
          show-overflow-tooltip
        />
        <el-table-column
          label="启用状态"
          prop="enabled"
          min-width="100"
          show-overflow-tooltip
          align="center"
        >
          <template #default="scope">
            <el-tag type="success" v-if="scope.row.enabled === 1">启用</el-tag>
            <el-tag type="info" v-else>停用</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          label="创建时间"
          prop="createTime"
          min-width="160"
          show-overflow-tooltip
          align="center"
        />
        <el-table-column
          label="创建人"
          prop="createdUserName"
          min-width="100"
          show-overflow-tooltip
        />
        <el-table-column
          label="更新时间"
          prop="lastUpdateTime"
          min-width="160"
          show-overflow-tooltip
          align="center"
        />
        <el-table-column
          label="更新人"
          prop="lastUpdatedUserName"
          min-width="100"
          show-overflow-tooltip
        /> -->
        <el-table-column fixed="right" label="操作" width="240" align="center">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              link
              @click="openDialogdetail(scope.row)"
              ><i-ep-search />
              查看
            </el-button>
            <el-button
              type="primary"
              size="small"
              link
              @click="openDialog(scope.row)"
              ><i-ep-edit />编辑</el-button
            >
            <el-button
              type="primary"
              size="small"
              link
              @click="deleteItem(scope.row.id)"
              ><i-ep-delete />删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        :background="true"
        :current-page="pageable.pageNum"
        :page-size="pageable.pageSize"
        :page-sizes="[10, 25, 50, 100]"
        :total="pageable.total"
        layout="total, sizes, prev, pager, next, jumper"
        class="mt-[20px]"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <mespurchasematerialconfig-edit
      :visible="addDialog.visible"
      :title="addDialog.title"
      :data="addDialog.data"
      @reset-table="(id:string) => (id?.length ? getTableList() : reset())"
      :is-readonly="addDialog.readvisible"
      @change-visible="changeVisible"
    />
    <!--物料选择-->
    <conten-select
      :visible="selectDialogSELECT.visible"
      @change-visible="changeVisibleSELECT"
      :plantId="searchParam.plantId"
      :brekList="brekList"
    />
    <!-- 导入 -->
    <ImportExcel ref="materialImportRef" />
    <!-- 导入失败错误信息弹窗 -->
    <upload-error-table
      ref="uploadErrorRef"
      :errorDataList="errorDataList"
      :promptDataList="promptDataList"
      :paramList="paramList"
      :listWorkOrder="listWorkOrder"
      @changelist="changelist"
    />
    <!-- 列设置 -->
    <ColSetting
      v-model:col-setting="tableColumns"
      v-model:search-setting="searchColumns"
      @search-handle="(e:boolean) => (showSearch = e)"
    />
  </div>
</template>

<script setup lang="tsx">
import { useTable, useDownload, useDictionary } from "@/utils/useTable";
import request from "@/utils/request";

defineOptions({
  name: "MESRAWMATERIALNEEDPLANDELIVERYCONFIG",
  inheritAttrs: false,
});

// 请求参数
const requestApi = "/mes/mespurchasematerialconfig/queryByPage";

// 是否需要分页
const pagination = true;

const initParam = {};

// 初始化搜索参数数据
const searchParamInit = {
  materialId: "",
  materialCode: "",
  classification: "",
  purchasingCycle: "",
  createTimeSearch: [],
  createTimeStart: "",
  createTimeEnd: "",
  lastUpdateTimeSearch: [],
  lastUpdateTimeStart: "",
  lastUpdateTimeEnd: "",
  enabled: "",
  deleted: "",
};

const deleteParam = {
  api: "/mes/mespurchasematerialconfig/delete",
  data: {},
};

// 数据请求错误后处理
function requestError() {}

const dataCallBack = ref(undefined); // 无需二次数据处理&不传赞数也行

// 表格操作 Hooks
const {
  tableData,
  pageable,
  searchParam,
  ids,
  getTableList,
  search,
  reset,
  handleSizeChange,
  handleCurrentChange,
  handleSelectionChange,
  handleTableDelete,
  loading,
}: any = useTable(
  requestApi,
  initParam,
  searchParamInit,
  pagination,
  dataCallBack.value,
  requestError,
  deleteParam
);

onMounted(() => {
  getTableList();
});

const addDialog = reactive<DialogOption>({
  visible: false,
  readvisible: false,
  title: "",
  data: {},
});

// 查询详情
async function getInfo(id: string) {
  request({
    url: `/mes/mespurchasematerialconfig/get/${id}`,
    method: "get",
  })
    .then((data) => {
      addDialog.data = data.data;
      addDialog.visible = true;
    })
    .catch((res) => {
      console.log(res);
    });
}

/** 打开原材料采购配置表表单弹窗 */
function openDialog(roleObj?: Object) {
  if (roleObj) {
    addDialog.title = "修改原材料采购配置表";
    getInfo(roleObj.id);
  } else {
    addDialog.title = "新增原材料采购配置表";
    addDialog.visible = true;
  }
  addDialog.readvisible = false;
}

/** 打开原材料采购配置表表单弹窗 详情 */
function openDialogdetail(roleObj?: any) {
  addDialog.title = "原材料采购配置表详情";
  getInfo(roleObj.id);
  addDialog.readvisible = true;
}

function changeVisible(value: boolean) {
  addDialog.visible = value;
  if (!value) {
    addDialog.data = {};
  }
}

function getcreateTime(data: any) {
  if (data) {
    searchParam.value.createTimeStart = data[0];
    searchParam.value.createTimeEnd = data[1];
  } else {
    searchParam.value.createTimeStart = "";
    searchParam.value.createTimeEnd = "";
  }
}
function getlastUpdateTime(data: any) {
  if (data) {
    searchParam.value.lastUpdateTimeStart = data[0];
    searchParam.value.lastUpdateTimeEnd = data[1];
  } else {
    searchParam.value.lastUpdateTimeStart = "";
    searchParam.value.lastUpdateTimeEnd = "";
  }
}

async function deleteItem(id: any) {
  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    const { data } = await request({
      url: `/mes/mespurchasematerialconfig/deleteItem/${id}`,
      method: "post",
    }).then((res) => {
      ElMessage.success("删除成功！");
    });
    search();
  });
}
//产品选择
const showWorkOrderSelect = () => {
  selectDialogSELECT.value.visible = true;
};
//选择物料弹窗
const selectDialogSELECT = ref({
  visible: false,
});
const changeVisibleSELECT = (val: boolean, data: any) => {
  selectDialogSELECT.value.visible = val;
  if (data) {
    searchParam.value.materialId = data.id;
    searchParam.value.materialCode = data.materialCode;
  }
};
const resetMaterial = () => {
  searchParam.value.materialId = "";
  searchParam.value.materialCode = "";
};
// 回显的数据
const brekList = ref([]);

// 导入周数据
const materialImportRef = ref();
const uploadErrorRef = ref();
const errorDataList = ref([]);
const promptDataList = ref([]);
const listWorkOrder = ref([]);
const paramList = ref({});
async function materialImportApiFunc(formdata: FormData, config: any) {
  await request
    .post("/mes/mespurchasematerialconfig/upload", formdata, config)
    .then((res: any) => {});
}
const changelist = () => {
  search();
};
const materialImport = () => {
  let newSearchParam = { ...searchParam.value };
  let params = {
    title: "导入原材料到货配置",
    tempApi: "/mes/mespurchasematerialconfig/exportTemp", //模板下载
    importApi: materialImportApiFunc, // 导入
    getTableList, // 成功后回调
    isShowTemp: true, // 是否显示下载模板
    fileTypes: ".xlsx",
    searchParam: newSearchParam,
    isOK: true, // 是否显示成功条数
  };
  materialImportRef.value.acceptParams(params);
};

const tableColumns = reactive([
  {
    prop: "classification",
    label: "分类",
    minWidth: 100,
    isShow: true,
    align: "left",
  },
  {
    prop: "materialName",
    label: "物料名称",
    minWidth: 100,
    isShow: true,
    align: "left",
  },
  {
    prop: "unit",
    label: "单位",
    minWidth: 100,
    isShow: true,
    align: "center",
    render: (scope: any) => useDictionary("MeasurementUnit", scope.row.unit),
  },
  {
    prop: "purchasingCycle",
    label: "采购周期",
    minWidth: 100,
    isShow: true,
    align: "left",
  },
  // {
  //   prop: "safetyFactor",
  //   label: "安全系数",
  //   minWidth: 100,
  //   isShow: true,
  //   align: "left",
  // },
  {
    prop: "produce",
    label: "采购影响(产能)",
    minWidth: 100,
    isShow: true,
    align: "left",
  },
  {
    prop: "weather",
    label: "采购影响(天气)",
    minWidth: 100,
    isShow: true,
    align: "left",
  },
  {
    prop: "quality",
    label: "采购影响(质量异常)",
    minWidth: 120,
    isShow: true,
    align: "left",
  },
  {
    prop: "shelfLife",
    label: "保质期（月）",
    minWidth: 100,
    isShow: true,
    align: "left",
  },
  {
    prop: "minimumPurchaseQuantity",
    label: "最小采购量",
    minWidth: 100,
    isShow: true,
    align: "left",
  },
  {
    prop: "remarks",
    label: "备注",
    minWidth: 100,
    isShow: true,
    align: "left",
  },
  {
    prop: "enabled",
    label: "启用状态",
    minWidth: 100,
    isShow: true,
    align: "center",
    render: (scope: any) =>
      scope.row.enabled == 1 ? (
        <el-tag type="success">启用</el-tag>
      ) : (
        <el-tag type="info">停用</el-tag>
      ),
  },
  {
    prop: "createTime",
    label: "创建时间",
    minWidth: 160,
    isShow: true,
    align: "center",
  },
  {
    prop: "createdUserName",
    label: "创建人",
    minWidth: 100,
    isShow: true,
    align: "left",
  },
  {
    prop: "lastUpdateTime",
    label: "更新时间",
    minWidth: 160,
    isShow: true,
    align: "center",
  },
  {
    prop: "lastUpdatedUserName",
    label: "更新人",
    minWidth: 100,
    isShow: true,
    align: "left",
  },
]);

const searchColumns = reactive([]);
</script>
